//
// Created by Leaf on 2025/8/18.
//

#ifndef LEDMATRIX_H
#define LEDMATRIX_H

#include <Arduino.h>
#include <SPI.h>
#include "global/GData.h"

// 默认引脚定义
//#ifndef LED_MATRIX_DIN_PIN
//#define LED_MATRIX_DIN_PIN D3
//#endif
//
//#ifndef LED_MATRIX_CLK_PIN
//#define LED_MATRIX_CLK_PIN D2
//#endif
//
//#ifndef LED_MATRIX_CS_PIN
//#define LED_MATRIX_CS_PIN 5
//#endif


// MAX7219寄存器地址
#define MAX7219_REG_NOOP         0x00
#define MAX7219_REG_DIGIT0       0x01
#define MAX7219_REG_DIGIT1       0x02
#define MAX7219_REG_DIGIT2       0x03
#define MAX7219_REG_DIGIT3       0x04
#define MAX7219_REG_DIGIT4       0x05
#define MAX7219_REG_DIGIT5       0x06
#define MAX7219_REG_DIGIT6       0x07
#define MAX7219_REG_DIGIT7       0x08
#define MAX7219_REG_DECODE_MODE  0x09
#define MAX7219_REG_INTENSITY    0x0A
#define MAX7219_REG_SCAN_LIMIT   0x0B
#define MAX7219_REG_SHUTDOWN     0x0C
#define MAX7219_REG_DISPLAY_TEST 0x0F

class LedMatrix {
private:
    uint8_t dinPin;
    uint8_t clkPin;
    uint8_t csPin;
    uint8_t numDevices;  // 设备数量
    uint8_t **state;    // 保存LED状态的二维数组

    /// 向指定设备发送命令和数据
    void transfer(uint8_t opcode, uint8_t data, uint8_t device);
    /// 通过SPI接口传输数据
    void spiTransfer(uint8_t opcode, uint8_t data, uint8_t device) const;
    /// 将缓冲区数据提交到显示屏
    void commit(); 

public:
    /// 构造函数，初始化引脚和设备数量
    LedMatrix(uint8_t dataPin = LED_MATRIX_DIN_PIN, 
              uint8_t clkPin = LED_MATRIX_CLK_PIN, 
              uint8_t csPin = LED_MATRIX_CS_PIN,
              uint8_t numDevices = 1);
    
    /// 初始化点阵屏
    void begin();
    /// 设置点阵屏亮度
    void setIntensity(uint8_t intensity);
    /// 清空点阵屏显示
    void clear();
    /// 设置指定位置LED的状态
    void setLed(uint8_t row, uint8_t col, bool state);
    /// 设置整行的显示
    void setRow(uint8_t row, uint8_t value);
    /// 设置整列的显示
    void setColumn(uint8_t col, uint8_t value);
    /// 绘制精灵图/图案
    void drawSprite(int8_t x, int8_t y, const uint8_t sprite[], uint8_t width, uint8_t height);
    /// 更新显示内容
    void update();
    
    // 新增的旋转显示函数
    void drawSpriteRotated(int8_t x, int8_t y, const uint8_t sprite[], uint8_t width, uint8_t height, uint16_t angle);
    
    // 新增的滚动显示函数
    void drawSpriteScrolling(int8_t x, int8_t y, const uint8_t sprite[], uint8_t width, uint8_t height, 
                            uint8_t direction, uint8_t steps, uint16_t delayMs);

    // 循环滚动显示函数
    void drawSpriteLoopScrolling(int8_t x, int8_t y, const uint8_t sprite[], uint8_t width, uint8_t height,
                                 uint8_t direction, uint16_t steps, uint16_t delayMs);

};

#endif //LEDMATRIX_H